package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("cart")

public class CartController {
    @Autowired
    private CatalogService catalogService;
    @GetMapping("viewCart")
    public String viewCart(HttpSession session, RedirectAttributes redirectAttributes){
        Account account =(Account)session.getAttribute("account");
        if(account==null){
            String value="您还未登录，请先登录";
            redirectAttributes.addFlashAttribute("msg",value);
            return "redirect:/account/signOnForm";
        }else {
            return "cart/cart";
        }
    }
    @GetMapping("/addItemToCart")
    public String addItemToCart(@RequestParam("workingItemId") String workingItemId, RedirectAttributes redirectAttributes, HttpSession session){

        Account loginUser =(Account)session.getAttribute("account");
        Cart cart =(Cart) session.getAttribute("cart");
        if(loginUser==null){
            String value="您未登录，请先登录";
            redirectAttributes.addFlashAttribute("msg",value);
            return "redirect:/account/signOnForm";
        }
        else {
            if (cart == null) {
                cart = new Cart();
            }
            if (cart.containsItemId(workingItemId)) {
                cart.incrementQuantityByItemId(workingItemId);
            } else {
                boolean isInStock = catalogService.isInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item, isInStock);
            }
            storeCart(cart, loginUser);

            session.setAttribute("cart",cart);
            return "redirect:/cart/viewCart";
        }

    }
    @GetMapping("removeItemFromCart")
    public String removeItemFromCart(@RequestParam("workingItemId")String workingItemId,HttpSession session){
        Account account=(Account)session.getAttribute("account");
        String username=account.getUsername();
        catalogService.deleteCart(username,workingItemId);
        fun2(session, account, catalogService);
        return "redirect:/cart/viewCart";
    }
    @PostMapping("updateCartQuantities")
    public String updateCartQuantities(HttpSession session,RedirectAttributes redirectAttributes, HttpServletRequest request){

        Cart cart = (Cart) session.getAttribute("cart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = cartItems.next();
            String  itemId = cartItem.getItem().getItemId();
            try {
                int quantity = Integer.parseInt(request.getParameter(itemId));

                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                session.setAttribute("errorMessage", "The Quantities of Item must be Integer!");
                return "/common/error";
            }
        }
        Account loginUser=(Account) session.getAttribute("account");
        storeCart(cart, loginUser);
        return "redirect:/cart/viewCart";


    }

    public void storeCart(Cart cart, Account loginUser) {
        catalogService.beforeStore(loginUser.getUsername());
        ShoppingCart shoppingCart = new ShoppingCart();
        for(int i = 0 ;i <cart.getCartItemList().size(); i++ ){
            shoppingCart.setIsDelete(0);
            shoppingCart.setIsUpdate(0);
            shoppingCart.setItemId(cart.getCartItemList().get(i).getItem().getItemId());
            shoppingCart.setQuantity(cart.getCartItemList().get(i).getQuantity());
            shoppingCart.setUserid(loginUser.getUsername());
            catalogService.store(shoppingCart);
        }
    }

    public static void fun2(HttpSession session, Account account, CatalogService catalogService) {
        List<CartItem> cartItemList = catalogService.getCart(account.getUsername());
        Cart cart = new Cart();
        if(cartItemList!=null) {
            for (CartItem cartItem : cartItemList) {
                boolean isInStock = catalogService.isInStock(cartItem.getItem().getItemId());
                cart.addItem(cartItem.getItem(), isInStock);
                cart.setQuantityByItemId(cartItem.getItem().getItemId(), cartItem.getQuantity());
            }
        }else {
            cart=null;
        }
        session.setAttribute("cart",cart);
    }
}
